<template>
  <div>
    <div class="plan-canlendar-page">
      <Calendar
        v-model:currentDate="currentDate"
        v-model:factoryAreaCode="factoryAreaCode"
        v-model:showSlider="showSlider"
        :planStatusList="planStatusList"
        :currentTask="currentTask"
        :taskData="taskData"
      />
      <TaskList
        v-show="showSlider"
        v-model:currentTask="currentTask"
        :currentDay="currentDay"
        :planStatusList="planStatusList"
        :taskData="taskData"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, onBeforeMount } from "vue";
import Calendar from "./components/Calendar.vue";
import TaskList from "./components/TaskList.vue";
import { monthDays } from "@pureadmin/utils";
import { checkTaskCalendar } from "@/api/erc/inspectTask";
import { queryDictData } from "@/api/common";
const currentDate = ref(new Date());
const factoryAreaCode = ref();
const showSlider = ref(false);
const currentTask = ref();
const currentDay = ref();
const taskData = ref({});
const yearRef = ref();
const monthRef = ref();
const planStatusList = ref([]);
// 补零函数
const addZero = (num: number) => {
  return num < 10 ? `0${num}` : num;
};
// 获取当前月份日期
const getMonthDays = date => {
  const dateArray = [];
  if (date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const daysNum = monthDays(date);
    for (let i = 1; i <= daysNum; i++) {
      dateArray.push(`${year}-${addZero(month)}-${addZero(i)}`);
    }
  } else {
    console.error("date值为undefined");
  }
  return dateArray;
};
const transformCalendarData = (data, dateArray) => {
  const calendarObj = {};
  if (data) {
    const newData = data.forEach(item => {
      calendarObj[item.date] = item.taskList;
    });
  }
  return calendarObj;
};
// 请求当前月份任务数据
const getTaskData = async (date?: Date) => {
  const newDate = date || new Date();
  const year = newDate.getFullYear();
  const month = newDate.getMonth() + 1;
  const day = newDate.getDate();
  currentDay.value = `${year}-${addZero(month)}-${addZero(day)}`;
  // 数据请求优化，年月不变，不重新请求数据
  // if (year === yearRef.value && month === monthRef.value) {
  //   return;
  // } else {
  yearRef.value = year;
  monthRef.value = month;
  // }
  const dateArray = getMonthDays(newDate);
  const data = await checkTaskCalendar({ year, month, facCode: factoryAreaCode.value });
  taskData.value = transformCalendarData(data, dateArray);
};
watch([currentDate, factoryAreaCode], () => {
  if (currentDate.value) {
    getTaskData(currentDate.value);
  }
});
// 获取状态下拉列表
const queryTaskStatusSelect = async () => {
  const tempPlanStatusList = await queryDictData({ typeCode: "ERC_CHECK_TASK_STATUS" });
  planStatusList.value = tempPlanStatusList || [];
};
onBeforeMount(() => {
  getTaskData();
  queryTaskStatusSelect();
});
</script>
<style lang="scss">
.plan-canlendar-page {
  display: flex;
  height: calc(100vh - 121px);
}
</style>
